package com.hmall.gateway.filters;

import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter , Ordered {

    private final JwtTool  jwtTool;

    private final AuthProperties  authProperties;
    private final AntPathMatcher  antPathMatcher = new AntPathMatcher();



    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取到请求体
        ServerHttpRequest request = exchange.getRequest();
        //判断是否放行
        if(isExclude(request.getPath().toString()))
        {
            //放行
            return chain.filter(exchange);
        }
        //获取token
        HttpHeaders headers = request.getHeaders();
        List<String> list = headers.get("authorization");
        String token = "";
        if(list != null && !list.isEmpty())
        {
            token = list.get(0);
        }
        //做登录校验
        Long userId = null;
        try{
            userId = jwtTool.parseToken(token);
        } catch (Exception e)
        {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }
        //将数据传递给下一个微服务
        String userinfo = userId.toString();
        exchange.mutate()
                .request(builder -> builder.header("userId", userinfo))
                .build();
        //放行
        return chain.filter(exchange);
    }

    private boolean isExclude(String path) {
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            if(antPathMatcher.match(excludePath, path))
            {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
